package com.wangsir.servlet;

import com.wangsir.entity.Clazz;
import com.wangsir.entity.Student;
import com.wangsir.service.ClazzService;
import com.wangsir.service.StudentService;
import com.wangsir.util.ApiResult;
import com.wangsir.util.MyUtil;
import com.wangsir.util.PagerVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@WebServlet("/student")
public class StudentServlet extends HttpServlet {
    private StudentService studentService = new StudentService();
    private ClazzService clazzService =  new ClazzService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        String r = req.getParameter("r");
        //只要不是修改和新增都是班级列表页面
        if(r == null) {
            String currentPage = req.getParameter("currentPage");
            //第一次请求这个方法的时候是不加参数的，给current一个默认的值，默认第一次访问是第一页
            if (currentPage == null) {
                currentPage = "1";
            }
            //String sno,String gender,String name,String clazzno
            String clazzNO = req.getParameter("clazzNO");
            System.out.println("========================================");
            System.out.println(clazzNO);
            String name = req.getParameter("name");
            String gender = req.getParameter("gender");
            String sno = req.getParameter("sno");
            PagerVO<Student> pageVo = studentService.page(Integer.parseInt(currentPage), 10,sno,gender, name,clazzNO);
            System.out.println("========================================");
            System.out.println(pageVo);
            pageVo.init();
            List<Clazz> clazzes  = clazzService.listAll();
            //1.高效方法设置
            HashMap<String, Clazz> map = new HashMap<String, Clazz>();
            for(Clazz clazz : clazzes){
                map.put(clazz.getClazzNo(),clazz);
            }
            for (Student student : pageVo.getList()) {
                student.setClazz(map.get(student.getClazzNO()));
            }
            //数据量大的时候效率比较低
            /*for (Student student : pageVo.getList()) {
                for(Clazz clazz : clazzes) {
                    if(Objects.equals(student.getClazzNO(),clazz.getClazzNo())){
                        student.setClazz(clazz);//把班级设置进去学生里面进去
                    }
                }
            }*/

            List<Student> list = pageVo.getList();
            //打印数据在服务器中
            for (Student s : list) {
                System.out.println(s);
            }
            req.setAttribute("clazzNO", clazzNO);
            req.setAttribute("name", name);
            req.setAttribute("gender", gender);
            req.setAttribute("sno", sno);
            req.setAttribute("pageVo", pageVo);
            req.getRequestDispatcher("/WEB-INF/view/student-list.jsp").forward(req, resp);
        }
        if("add".equals(r)){
            boolean isPermission = MyUtil.hasPermission(req,resp,false,"admin");
            //没有权限就不进行跳转，直接return
            if(!isPermission){
                return;
            }
            System.out.println("查看是否有传递数据：" + req.getParameter(  "cs"));
            req.getRequestDispatcher("/WEB-INF/view/student-add.jsp").forward(req, resp);
        }
        if("edit".equals(r)){
            boolean isPermission = MyUtil.hasPermission(req,resp,false,"admin");
            //没有权限就不进行跳转，直接return
            if(!isPermission){
                return;
            }
            String sno = req.getParameter("sno");
            System.out.println("sno:" + sno);
            Student student = studentService.getStudentBySno(sno);
            req.setAttribute("entity",student);
            System.out.println(student);
            req.getRequestDispatcher("/WEB-INF/view/student-edit.jsp").forward(req, resp);
        }
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //新增 修改 删除
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        //
        String r = req.getParameter("r");
        List<Clazz> cs = clazzService.listAll();
        System.out.println(cs);
        if("add".equals(r) || "edit".equals(r)) {
            boolean isPermission = MyUtil.hasPermission(req,resp,true,"admin");
            //没有权限就不进行跳转，直接return
            if(!isPermission){
                return;
            }
            Student student = new Student();
            student.setSno(req.getParameter("sno"));
            student.setPassword(req.getParameter("password"));
            student.setName(req.getParameter("name"));
            student.setTele(req.getParameter("tele"));
            //自定义工具类将字符串变为日期类型
            student.setEnterDate(MyUtil.strToDate(req.getParameter("enterDate")));
            student.setAge(Integer.parseInt(req.getParameter("age")));
            student.setGender(req.getParameter("gender"));
            student.setAddress(req.getParameter("address"));
            student.setClazzNO(req.getParameter("clazzNO"));
            if("add".equals(r)){
                //add
                //把所有的班级创建出来
                req.setAttribute("cs", cs);
                System.out.println("你要添加的对象是：" + student);
                String msg = studentService.insertStudent(student);
                if(msg != null){
                    resp.getWriter().write(ApiResult.json(false,msg));
                    return;
                }else{
                    resp.getWriter().write(ApiResult.json(true,"保存学生成功！"));
                    return;
                }
            }else{
                //edit
                req.setAttribute("cs",cs);
                System.out.println("您要修改的对象是: " + student);
                String msg = studentService.updateStudent(student);
                if(msg != null){
                resp.getWriter().write(ApiResult.json(false,msg));
                return;
                }else{
                resp.getWriter().write(ApiResult.json(true,"更新学生成功！"));
                return;
                }
            }
        }else{
            boolean isPermission = MyUtil.hasPermission(req,resp,true,"admin");
            //没有权限就不进行跳转，直接return
            if(!isPermission){
                return;
            }
            //del
            //下面的这个变量名必须要和前端传过来的data的属性名称一样，否则属性名称是无法进行解析的
            String sno = req.getParameter("sno");
            int result = studentService.deleteBySno(sno);
            System.out.println(result);
            if(result ==  0){
                resp.getWriter().write(ApiResult.json(false,"删除失败，请联系管理员处理！"));
                return;
            }else{
                resp.getWriter().write(ApiResult.json(true,"删除学生成功！"));
                return;
            }

        }
    }
}
